package com.sproutcat.security;

import org.springframework.util.StreamUtils;

import java.io.InputStream;

import static com.sproutcat.security.AesSample.*;
import static com.sproutcat.security.RsaSample.*;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * AES + RSA 的加密解密（用于数据传输）
 * @author tzg
 */
public class AesAndRsaSample {

    public static void main(String[] args) throws Exception {
        InputStream is = RsaSample.class.getResourceAsStream("/test.json");
        String testDate = StreamUtils.copyToString(is, UTF_8);
//        String testDate = "[{\n" +
//                "  \"name\": \"test1\",\n" +
//                "  \"age\": 21\n" +
//                "},{\n" +
//                "  \"name\": \"test2\",\n" +
//                "  \"age\": 26\n" +
//                "}]";
        //String testDate = "Hello world!";

        RsaKey keyPair = generateRsaKeys();
        String aesKey = randomAesKey();
        System.out.println("AES 密钥: " + aesKey);

        long startTime = System.currentTimeMillis();
        // 开始加密：使用 ASE 加密数据，再使用 RSA 加密 AES 的随机密钥
        String encryptAesKey= encryptByPublicKey(aesKey, keyPair.getPublicKey());
        String encryptDate = encrypt(testDate, aesKey);
        String resData = String.format("{\"data\": \"%s\", \"signature\": \"%s\"}", encryptDate, encryptAesKey);
        System.out.println("AES+RSA 加密结果: " + resData);
        System.out.println("AES+RSA 加密耗时：" + (System.currentTimeMillis() - startTime) + " ms");

        System.out.println();

        startTime = System.currentTimeMillis();
        // 开始解密：先用 RSA 私钥解密 AES 的密钥，再用解密后的 AES 密钥解密数据
        String decryptAesKey = decryptByPrivateKey(encryptAesKey, keyPair.getPrivateKey());
        System.out.println("RSA 解密 AES 密钥: " + decryptAesKey);
        String decryptData = decrypt(encryptDate, decryptAesKey);
        System.out.println("AES 解密结果: " + decryptData);
        System.out.println("AES+RSA 解密耗时：" + (System.currentTimeMillis() - startTime) + " ms");
    }

}
